import requests
import json
import time
from urllib.parse import urlencode
import random

def get_jsessionid():
    try:
        with open('8_Cookie', 'r') as file:
            for line in file:
                if line:
                    return line
    except FileNotFoundError:
        print("8_Cookie file not found.")
    return None

def load_processed_ids():
    """从文件加载已处理的ID"""
    try:
        with open('8_ID', 'r') as f:
            return set(line.strip() for line in f if line.strip())
    except FileNotFoundError:
        return set()


def get_id_and_submit(ht_user):
    jsessionid = get_jsessionid()
    # 提交审核模块开始
    url = 'http://133.96.94.70:8081/nrms/odnImprove/findAllOdnImproves.action'
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '670',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': jsessionid,
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }
    where = {
        "applyDateStart": "",
        "applyDateEnd": "",
        "htType": "all",
        "source": "0",
        "status": "4",
        "htLvl": "all",
        "cityCode": "1310",
        "areaCode": "131083",
        "htComplete": "all",
        "htState": "all",
        "htId": "",
        "htRk": "all",
        "htUser": ht_user,  
        "htOrderId": "",
        "htExampleId": "",
        "finishDateStart": "",
        "finishDateEnd": "",
        "htResId": "",
        "htResName": "",
        "htOrderType": "all",
        "htXJExampleId": ""
    }
    data = {
        'where': json.dumps(where),
        'sort': 'CREATE_TIME',
        'order': 'asc',
        'page': 1,
        'rows': 100
    }

    try:
        response = requests.post(url, headers=headers, data=data)
        if response.status_code == 200:
            result = response.json()
            for row in result["rows"]:
                id = row["ID"]
                order_id = row["ORDER_ID"]
                top_order_id = row["TOP_ORDER_ID"]
                risk_mitigation_plan = row["RISK_MITIGATION_PLAN"]
                processed_ids = load_processed_ids()
                if id in processed_ids:
                    print(f" {id} 跳过")
                    continue
                if risk_mitigation_plan == "分纤箱整治" and top_order_id == None:
                    get_info_by_id_url = "http://133.96.94.70:8081/nrms/odnImprove/getOdnImproveById.action"
                    get_info_headers = {
                        "Accept": "application/json, text/javascript, */*; q=0.01",
                        "Accept-Encoding": "gzip, deflate",
                        "Accept-Language": "zh-CN,zh;q=0.9",
                        "Connection": "keep-alive",
                        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                        "Cookie": jsessionid,  # 注意：Cookie可能需要动态获取
                        "Host": "133.96.94.70:8081",
                        "Origin": "http://133.96.94.70:8081",
                        "Referer": "http://133.96.94.70:8081/nrms/page/odnImprove/odnimprovelist.jsp",
                        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.200 Safari/537.36 Qaxbrowser",
                        "X-Requested-With": "XMLHttpRequest"
                    }

                    get_info_params = {
                        "id": id
                    }

                    get_info_data = urlencode(get_info_params)

                    try:
                        get_info_response = requests.post(get_info_by_id_url, headers=get_info_headers, data=get_info_data, timeout=10)
                        time.sleep(0.5)
                        if get_info_response.status_code == 200:
                            pass
                            # print("详细信息请求成功")
                        else:
                            print(f"请求失败，状态码：{get_info_response.status_code}")
                            print(get_info_response.text)

                    except requests.exceptions.RequestException as e:
                        print(f"请求异常：{e}")

                    is_odn_complete_url = "http://133.96.94.70:8081/nrms/odnImprove/isOdnInfoComplete.action"
                    is_odn_headers = {
                        "Accept": "application/json, text/javascript, */*; q=0.01",
                        "Accept-Encoding": "gzip, deflate",
                        "Accept-Language":  "zh-CN,zh;q=0.9",
                        "Connection": "keep-alive",
                        "Content-Length": "39",
                        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                        "Cookie": jsessionid,
                        "Host": "133.96.94.70:8081",
                        "Origin": "http://133.96.94.70:8081",
                        "Referer": "http://133.96.94.70:8081/nrms/page/odnImprove/odnimprovelist.jsp",
                        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
                        "X-Requested-With": "XMLHttpRequest"
                    }
                    payload = {
                        "id": id
                    }
                    is_odn_complete_response = requests.post(is_odn_complete_url,headers=is_odn_headers,data=payload)
                    flag = is_odn_complete_response.json()["success"]
                    if flag == True:
                        # print("判断该订单为ODN订单")
                        submit_url = "http://133.96.94.70:8081/nrms/odnImprove/submit.action"
                        submit_headers = {
                            "Accept": "application/json, text/javascript, */*; q=0.01",
                            "Accept-Encoding": "gzip, deflate",
                            "Accept-Language": "zh-CN,zh;q=0.9",
                            "Connection": "keep-alive",
                            "Content-Type": "application/json;charset=UTF-8",
                            "Cookie": jsessionid,  # 需替换为有效Cookie
                            "Host": "133.96.94.70:8081",
                            "Origin": "http://133.96.94.70:8081",
                            "Referer": "http://133.96.94.70:8081/nrms/page/odnImprove/odnimprovelist.jsp",
                            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.200 Safari/537.36 Qaxbrowser",
                            "X-Requested-With": "XMLHttpRequest"
                        }
                        data = {
                            "receiverUserList": [
                                {"userId": "10300000014434", "roleId": "10200000002957"},
                                {"userId": "10300000002041", "roleId": "10200000002957"},
                                {"userId": "10300000009405", "roleId": "10200000002957"},
                                {"userId": "10300000008798", "roleId": "10200000002957"},
                                {"userId": "10300000002034", "roleId": "10200000002957"},
                                {"userId": "10300000002038", "roleId": "10200000002957"},
                                {"userId": "10300000009194", "roleId": "10200000002957"},
                                {"userId": "10300000009403", "roleId": "10200000002957"},
                                {"userId": "10300000009400", "roleId": "10200000002957"},
                                {"userId": "10300000009402", "roleId": "10200000002957"},
                                {"userId": "10300000013183", "roleId": "10200000002957"},
                                {"userId": "10300000013855", "roleId": "10200000002957"},
                                {"userId": "10300000008800", "roleId": "10200000002957"},
                                {"userId": "10300000008799", "roleId": "10200000002957"},
                                {"userId": "10300000001984", "roleId": "10200000002957"},
                                {"userId": "10300000018234", "roleId": "10200000002957"},
                                {"userId": "10300000030274", "roleId": "10200000002957"}
                            ],
                            "sendMsg": False,  # 注意：Python中布尔值需用False/True（首字母大写）
                            "bizId": id
                        }
                        submit_response = requests.post(submit_url, headers=submit_headers, json=data, timeout=10)
                        time.sleep(2)
                        if submit_response.json()["success"] == True and submit_response.json()["msg"] == "提交成功":
                            print(f"{id} submit successful!")
                        else:
                            print(f"{id} submit failed!")         
        else:
            print(f"请求失败，状态码: {response.status_code}")
    except requests.RequestException as e:
        print(f"请求发生错误: {e}")
    # 提交审核模块结束

def get_odn_by_id(bz_id,id):
    # 目标URL
    url = 'http://133.96.94.70:8081/nrms/odnImprove/getOdnImproveById.action'
    s = get_jsessionid()
    # 请求头
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': s,
        'Host': '133.96.94.70:8081',
        'Origin': 'http://133.96.94.70:8081',
        'Referer': f'http://133.96.94.70:8081/nrms/page/odnImprove/workTask/odnimproveInfo.jsp?id={bz_id}&rid={id}',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }

    # 请求参数
    data = {
        'id': f"{bz_id}"
    }

    try:
        # 发送POST请求
        response = requests.post(url, headers=headers, data=data)
        
        # 检查响应状态码
        if response.status_code == 200:
            # 尝试解析JSON响应
            try:
                return response.json()
                
            except ValueError:
                print(response.text)
    except requests.exceptions.RequestException as e:
        print(f"请求发生错误: {e}")
        time.sleep(3)  # 失败后延迟3秒重试    

def submit_flow(bz_id,id,example_id):
    
    url = "http://133.96.94.70:8081/nrms/odnImprove/submitFlow.action"  

    # 动态生成实时时间戳（更新Referer中的timer参数）  
    current_timestamp = int(time.time() * 1000)  
    referer_url = f"http://133.96.94.70:8081/nrms/page/odnImprove/workTask/flowForm.jsp?rid={id}&listType=doList&timer={current_timestamp}"  

    # 优化请求头（移除敏感字段，添加指纹参数）  
    session = get_jsessionid()
    headers = {  
        "Accept": "application/json, text/javascript, */*; q=0.01",  
        "Accept-Encoding": "gzip, deflate",  
        "Accept-Language": "zh-CN,zh;q=0.9",  
        "Connection": "keep-alive",  
        "Content-Type": "application/json;charset=UTF-8",  
        "Cookie": session,  # 替换为有效会话ID  
        "Host": "133.96.94.70:8081",  
        "Origin": "http://133.96.94.70:8081",  
        "Referer": referer_url,  
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",  
        "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",  
        # 移除 X-Requested-With 或改为其他值  
    }  

    # 请求参数（JSON格式）  
    payload = {  
        "amount": "0",  
        "bizId": f"{bz_id}",  
        "exampleId": f"{example_id}",  
        "exampleTaskSids": [id],  
        "receiverUserList": [],  
        "remark": "",  
        "sendMsg": False,   
        "taskId": 100100,  
        "userId": "103000000002034",  
        "zzfs": "13"  
    }  

    # 会话保持  
    session = requests.Session()  
    session.headers.update(headers)  

    try:  
        # 发送POST请求（自动处理JSON序列化）  
        response = session.post(url, json=payload)  
        time.sleep(6)
        # print(f"Status Code: {response.status_code}")  
        if response.status_code == 200:  
            print(f"{bz_id} 最后提交成功,订单发送到TOP,流程结束.")
            # print("Response JSON:", response.json())  
        else:  
            print("Request Failed:", response.text)  

    except requests.exceptions.RequestException as e:  
        print(f"Error: {e}")  
        time.sleep(3)   


def judge_is_node_end(bz_id):
    session = get_jsessionid()
    url = "http://133.96.94.70:8081/nrms/odnImproveFlow/getNextNodeIsEnd.action"  

    # 动态生成实时时间戳（更新Referer中的timer参数）  
    current_timestamp = int(time.time() * 1000)  
    referer_url = f"http://133.96.94.70:8081/nrms/page/odnImprove/workTask/flowForm.jsp?rid=20000000461123&listType=doList&timer={current_timestamp}"  

    # 优化请求头（移除可能暴露身份的字段，添加浏览器指纹）  
    headers = {  
        "Accept": "application/json, text/javascript, */*; q=0.01",  
        "Accept-Encoding": "gzip, deflate",  
        "Accept-Language": "zh-CN,zh;q=0.9",  
        "Connection": "keep-alive",  
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",  
        "Cookie": session,  # 替换为有效会话Cookie  
        "Host": "133.96.94.70:8081",  
        "Origin": "http://133.96.94.70:8081",  
        "Referer": referer_url,  
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",  
        "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",  # 新增UA客户端提示  
        # 移除 X-Requested-With 或改为其他值（如 "Chrome"）  
    }  

    # 请求参数  
    data = {  
        "taskId": "100100",  
        "bzId": f"{bz_id}" 
    }  

    # 会话保持（模拟登录流程）  
    session = requests.Session()  
    session.headers.update(headers)  

    try:  
        # 发送POST请求  
        response = session.post(url, data=data)  
        # print(f"Status Code: {response.status_code}")  
        if response.status_code == 200:  
            # 尝试解析JSON响应  
            try:  
                return True
            except ValueError:  
                print("Response Text:", response.text)  
        else:  
            print("Request Failed:", response.reason)  

    except requests.exceptions.RequestException as e:  
        print(f"Error: {e}")  
        time.sleep(3)  # 失败后延迟重试  


def get_odn_list():
    sessionid = get_jsessionid()
    # 签收模块开始
    url = "http://133.96.94.70:8081/nrms/odnImproveFlow/getOdnFlowList.action"
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Length": "80",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie": sessionid,
        "Host": "133.96.94.70:8081",
        "Origin": "http://133.96.94.70:8081",
        "Referer": "http://133.96.94.70:8081/nrms/page/odnImprove/workTask/todoList.jsp?flowId=4001",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    data = {
        "where": json.dumps({"flowId": "4001", "listType": "TODOLIST"}), # mustdo mustdo mustdo,dump json.
        "page": 0,
        "rows": 50
    }

    try:
        response = requests.post(url, headers=headers, data=data)
        time.sleep(3)
        if response.status_code == 200:
            result = response.json()
            for row in result["rows"]:
                aid = row["AID"]
                accept_url = "http://133.96.94.70:8081/nrms/odnImproveFlow/accept.action"
                accept_headers = {
                    "Accept": "application/json, text/javascript, */*; q=0.01",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9",
                    "Connection": "keep-alive",
                    "Content-Length": "39",
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "Cookie": sessionid,
                    "Host": "133.96.94.70:8081",
                    "Origin": "http://133.96.94.70:8081",
                    "Referer": "http://133.96.94.70:8081/nrms/page/odnImprove/workTask/todoList.jsp?flowId=4001",
                    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
                    "X-Requested-With": "XMLHttpRequest"
                }
                accept_payload = {
                    "exampleTaskSidList[]": aid 
                }
                accept_response = requests.post(accept_url,headers=accept_headers,data=accept_payload)
                if accept_response.status_code == 200:
                    print(f"{aid} 签收成功.")
                    #print("最后提交开始")
                    get_odn_sid_url = 'http://133.96.94.70:8081/nrms/odnImproveFlow/getOdnFlowTaskBySid.action'
                    cur_time = int(time.time() * 1000)
                    # print(cur_time)
                    # 请求头
                    get_odn_sid_headers = {
                        'Accept': 'application/json, text/javascript, */*; q=0.01',
                        'Accept-Encoding': 'gzip, deflate',
                        'Accept-Language': 'zh-CN,zh;q=0.9',
                        'Connection': 'keep-alive',
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'Cookie': sessionid,
                        'Host': '133.96.94.70:8081',
                        'Origin': 'http://133.96.94.70:8081',
                        'Referer': f'http://133.96.94.70:8081/nrms/page/odnImprove/workTask/flowForm.jsp?rid={aid}&listType=doList&flowId=4001&timer={cur_time}',
                        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
                        'X-Requested-With': 'XMLHttpRequest'
                    }

                    # 请求参数
                    get_odn_sid_data = {
                        'flowExampleSid': aid
                    }

                    try:
                        # print("开始通过AID查询")
                        get_odn_sid_response = requests.post(get_odn_sid_url, headers=get_odn_sid_headers, data=get_odn_sid_data)
                        
                        # 检查响应状态码
                        if get_odn_sid_response.status_code == 200:
                            # 尝试解析JSON响应
                            get_odn_sid_data = get_odn_sid_response.json()
                            get_odn_sid_id = get_odn_sid_data["ID"]
                            get_odn_sid_bzid = get_odn_sid_data["BZID"]
                            time.sleep(0.5)

                            info = get_odn_by_id(get_odn_sid_bzid,get_odn_sid_id)
                            example_id = info["obj"]["EXAMPLEID"]

                            time.sleep(3)
                            flag = judge_is_node_end(get_odn_sid_bzid)

                            if flag == True:
                                submit_flow(bz_id=get_odn_sid_bzid,id=get_odn_sid_id,example_id=example_id)
                        else:
                            print("通过AID查询失败.")
                    except requests.exceptions.RequestException as e:
                        print(f"请求发生错误: {e}")
    except requests.RequestException as e:
         print(f"请求发生错误: {e}")
    
        


if __name__ == "__main__":
    users = ["杨东兴","张瑶瑶"]
    for user in users:
        print(f"当前请求的 htUser 为: {user}")
        get_id_and_submit(user)
        time.sleep(0.5)
    # print("提交结束，开始签收")
    get_odn_list()
